import 'dart:io';

import 'package:bwt_ad_flutter_example/page/MainPage.dart';
import 'package:bwt_ad_flutter_example/util/Log.dart';
import 'package:bwt_ad_flutter_example/widget/SimpleWidget.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:bwt_ad_flutter/ad/loader/BwtSplashAdLoader.dart';

class SplashAdLauncherPage extends StatefulWidget {
  const SplashAdLauncherPage({super.key});

  @override
  State<StatefulWidget> createState() => _SplashState();
}

class _SplashState extends State<SplashAdLauncherPage> {
  BwtSplashAdLoader? _splashAdLoader;
  bool _jumped = false;

  @override
  Widget build(BuildContext context) {
    _showSplashAd();
    return SimpleWidget(
      width: double.infinity,
      height: double.infinity,
      color: Colors.white,
    );
  }

  @override
  void dispose() {
    _splashAdLoader?.release();
    super.dispose();
  }

  /// 加载展示开屏广告
  void _showSplashAd() {
    _splashAdLoader?.release();

    // 构建开屏广告加载器
    _splashAdLoader = BwtSplashAdLoader();

    // 设置广告加载成功监听
    _splashAdLoader?.onAdLoad = (bwtAd) {
      Log.d('开屏广告加载成功...');
    };

    // 设置广告加载失败监听
    _splashAdLoader?.onAdFailed = (msg) {
      Log.d('开屏广告加载失败, $msg');
      // 开屏广告加载失败跳转到首页
      _pushHome();
    };

    // 设置广告展示监听
    _splashAdLoader?.onAdExpose = (bwtAd) {
      Log.d('开屏广告展示成功...');
    };

    // 设置广告被点击监听
    _splashAdLoader?.onAdClick = (bwtAd) {
      Log.d('开屏广告被点击...');
    };

    // 设置广告关闭监听
    _splashAdLoader?.onAdClose = (bwtAd) {
      Log.d('开屏广告被关闭...');
      // 开屏广告关闭，跳转到首页
      _pushHome();
    };

    // 加载并展示开屏广告，设置logoName和backgroundName时需确认以下两条规则
    // Android端应在drawable或mipmap中有相应文件
    // iOS端应有相应名字的imageset
    _splashAdLoader?.loadAd(
      // 广告位ID，不同端的广告位ID可能不一致，需替换成自己相应端的广告位ID
      posId: Platform.isAndroid ? '18868947' : '06705202',
      // 底部展示的logo图片名称（不带后缀），不传则没有底部logo组件（高度为156）
      logoName: 'splash_ad_logo',
      // 加载开屏广告等待过程中的占位背景图（不带后缀），不传则默认是白色背景
      backgroundName: 'splash_ad_background',
    );
  }

  /// 跳转到首页
  void _pushHome() {
    // iOS 获取广告失败也会走 close 回调，此标记可避免重复跳转
    if (_jumped) return;

    _jumped = true;
    Navigator.pushReplacement(context, CupertinoPageRoute(builder: (context) {
      return const MainPage();
    }));
  }
}
